/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.im.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.im.bean.ImMsgBizEmployeeRecent;
import com.yami.shop.im.bean.ImMsgBizUser;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.bo.ShopSessionInfo;
import com.yami.shop.im.bo.SysSessionInfo;
import com.yami.shop.im.bo.UserSessionInfo;
import com.yami.shop.im.constants.MsgRead;
import com.yami.shop.im.constants.MsgType;
import com.yami.shop.im.constants.SendType;
import com.yami.shop.im.constants.WhoSend;
import com.yami.shop.im.dao.ImMsgBizUserHistoryMapper;
import com.yami.shop.im.param.MessageInfo;
import com.yami.shop.im.service.ImMsgBizEmployeeRecentService;
import com.yami.shop.im.service.ImMsgBizUserHistoryService;
import com.yami.shop.im.service.ImMsgBizUserService;
import com.yami.shop.im.vo.MsgItem;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.sys.comment.model.ShopEmployee;
import com.yami.shop.sys.comment.model.SysUser;
import com.yami.shop.sys.comment.service.ShopEmployeeService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author LZK
 * @date 2021-04-01 17:22:48
 */
@Service
@AllArgsConstructor
public class ImMsgBizUserHistoryServiceImpl extends ServiceImpl<ImMsgBizUserHistoryMapper, ImMsgBizUserHistory> implements ImMsgBizUserHistoryService {

    private final ImMsgBizUserHistoryMapper imMsgBizUserHistoryMapper;

    private final ImMsgBizUserService imMsgBizUserService;

    private final ImMsgBizEmployeeRecentService imMsgBizEmployeeRecentService;

    private final ShopDetailService shopDetailService;

    private final ShopEmployeeService shopEmployeeService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveHistory(Integer sendType, Long bizId, String userId, Long employeeId, Integer type, String content, Integer whoSend) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getOne(new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getSendType, sendType).eq(ImMsgBizUser::getBizId, bizId).eq(ImMsgBizUser::getUserId, userId));
        if (Objects.isNull(imMsgBizUser)) {
            imMsgBizUser = new ImMsgBizUser();
            imMsgBizUser.setSendType(sendType);
            imMsgBizUser.setBizId(bizId);
            imMsgBizUser.setUserId(userId);
            imMsgBizUser.setBizUnreadNum(0);
            imMsgBizUser.setUserUnreadNum(0);
            imMsgBizUser.setCreateTime(LocalDateTime.now());
            imMsgBizUser.setUpdateTime(LocalDateTime.now());
            imMsgBizUserService.save(imMsgBizUser);
        }
        ImMsgBizUserHistory imMsgBizUserHistory = new ImMsgBizUserHistory();
        imMsgBizUserHistory.setTzImMsgBizUserId(imMsgBizUser.getId());
        imMsgBizUserHistory.setSendType(sendType);
        imMsgBizUserHistory.setBizId(bizId);
        imMsgBizUserHistory.setUserId(userId);
        imMsgBizUserHistory.setEmployeeId(employeeId);
        imMsgBizUserHistory.setType(type);
        imMsgBizUserHistory.setContent(content);
        imMsgBizUserHistory.setWhoSend(whoSend);
        if (Objects.equals(whoSend, WhoSend.EMPLOYEE)) {
            imMsgBizUserHistory.setUserUnread(MsgRead.UNREAD);
            imMsgBizUserHistory.setEmployeeUnread(MsgRead.READ);
        } else if (Objects.equals(whoSend, WhoSend.USER)) {
            imMsgBizUserHistory.setUserUnread(MsgRead.READ);
            imMsgBizUserHistory.setEmployeeUnread(MsgRead.UNREAD);
        }
        imMsgBizUserHistory.setCreateTime(LocalDateTime.now());
        imMsgBizUserHistory.setUpdateTime(LocalDateTime.now());
        this.save(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Override
    public MsgItem getUserPlatformMsgItem(SysSessionInfo sysSessionInfo, UserSessionInfo userSessionInfo, ImMsgBizUserHistory imMsgBizUserHistory) {
        MsgItem msgItem = new MsgItem();
        msgItem.setChatType(imMsgBizUserHistory.getSendType());
        msgItem.setUserId(userSessionInfo.getUserId());
        msgItem.setUserHeadUrl(userSessionInfo.getPic());
        msgItem.setUserName(userSessionInfo.getNickName());
        msgItem.setShopId(sysSessionInfo.getUserId());
        msgItem.setShopName(sysSessionInfo.getNickName());
        msgItem.setItemId(imMsgBizUserHistory.getId());
        msgItem.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
        // todo 东8区，不应该写死"+8"后续优化
        msgItem.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        msgItem.setTimeStr(DateUtil.format(imMsgBizUserHistory.getCreateTime(), "yyyy/MM/dd HH:mm"));
        msgItem.setContent(imMsgBizUserHistory.getContent());
        msgItem.setType(imMsgBizUserHistory.getType());
        msgItem.setSource(imMsgBizUserHistory.getWhoSend());
        msgItem.setUserUnread(imMsgBizUserHistory.getUserUnread());
        msgItem.setEmployeeUnread(imMsgBizUserHistory.getEmployeeUnread());
        msgItem.setCreateTime(imMsgBizUserHistory.getCreateTime());
        msgItem.setUpdateTime(imMsgBizUserHistory.getUpdateTime());
        return msgItem;
    }

    @Override
    public MsgItem getUserShopMsgItem(ShopSessionInfo shopSessionInfo, UserSessionInfo userSessionInfo, ImMsgBizUserHistory imMsgBizUserHistory) {
        MsgItem msgItem = new MsgItem();
        msgItem.setChatType(imMsgBizUserHistory.getSendType());
        msgItem.setUserId(userSessionInfo.getUserId());
        msgItem.setUserHeadUrl(userSessionInfo.getPic());
        msgItem.setUserName(userSessionInfo.getNickName());
        msgItem.setShopLogo(shopSessionInfo.getPic());
        msgItem.setShopId(shopSessionInfo.getShopId());
        msgItem.setShopName(shopSessionInfo.getShopName());
        msgItem.setItemId(imMsgBizUserHistory.getId());
        msgItem.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
        // todo 东8区，不应该写死"+8"后续优化
        msgItem.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        msgItem.setTimeStr(DateUtil.format(imMsgBizUserHistory.getCreateTime(), "yyyy/MM/dd HH:mm"));
        msgItem.setContent(imMsgBizUserHistory.getContent());
        msgItem.setType(imMsgBizUserHistory.getType());
        msgItem.setSource(imMsgBizUserHistory.getWhoSend());
        msgItem.setUserUnread(imMsgBizUserHistory.getUserUnread());
        msgItem.setEmployeeUnread(imMsgBizUserHistory.getEmployeeUnread());
        msgItem.setCreateTime(imMsgBizUserHistory.getCreateTime());
        msgItem.setUpdateTime(imMsgBizUserHistory.getUpdateTime());
        return msgItem;
    }

    @Override
    public Page<MsgItem> getUserPlatformHistory(SysUser sysUser, MessageInfo messageInfo, Long bizId, String userId, UserSessionInfo userSessionInfo) {
        SysSessionInfo sysSessionInfo = new SysSessionInfo();
        sysSessionInfo.setUserId(sysUser.getUserId());
        sysSessionInfo.setNickName(sysUser.getNickName());
        PageParam<ImMsgBizUserHistory> pageParam = new PageParam<>();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageParam.setCurrent(messageInfo.getCurrent());
            pageParam.setSize(messageInfo.getSize());
        }
        Page<ImMsgBizUserHistory> history = this.page(pageParam, new LambdaQueryWrapper<ImMsgBizUserHistory>()
                .eq(ImMsgBizUserHistory::getSendType, messageInfo.getSendType()).eq(ImMsgBizUserHistory::getBizId, bizId).eq(ImMsgBizUserHistory::getUserId, userId).orderByDesc(ImMsgBizUserHistory::getId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getRecords();
        List<MsgItem> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItem msgItem = this.getUserPlatformMsgItem(sysSessionInfo, userSessionInfo, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        Page<MsgItem> msgItemPage = new Page<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setRecords(msgItems);
        return msgItemPage;
    }

    @Override
    public Page<MsgItem> getUserShopHistory(ShopDetail shopDetail, MessageInfo messageInfo, Long bizId, String userId, UserSessionInfo userSessionInfo) {
        ShopSessionInfo shopSessionInfo = new ShopSessionInfo();
        shopSessionInfo.setShopName(shopDetail.getShopName());
        shopSessionInfo.setPic(shopDetail.getShopLogo());
        shopSessionInfo.setShopId(shopDetail.getShopId());
        PageParam<ImMsgBizUserHistory> pageParam = new PageParam<>();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageParam.setCurrent(messageInfo.getCurrent());
            pageParam.setSize(messageInfo.getSize());
        }
        Page<ImMsgBizUserHistory> history = this.page(pageParam, new LambdaQueryWrapper<ImMsgBizUserHistory>()
                .eq(ImMsgBizUserHistory::getSendType, messageInfo.getSendType()).eq(ImMsgBizUserHistory::getBizId, bizId).eq(ImMsgBizUserHistory::getUserId, userId).orderByDesc(ImMsgBizUserHistory::getId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getRecords();
        List<MsgItem> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItem msgItem = this.getUserShopMsgItem(shopSessionInfo, userSessionInfo, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        Page<MsgItem> msgItemPage = new Page<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setRecords(msgItems);
        return msgItemPage;
    }

    @Override
    public Page<MsgItem> getShopUserHistory(YamiShopUser shopUser, MessageInfo messageInfo, User user) {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopUser.getShopId());
        ShopEmployee shopEmployee = shopEmployeeService.getShopEmployeeById(shopUser.getEmployeeId());
        ShopSessionInfo shopSessionInfo = new ShopSessionInfo();
        shopSessionInfo.setShopName(shopDetail.getShopName());
        shopSessionInfo.setPic(shopDetail.getShopLogo());
        shopSessionInfo.setShopId(shopDetail.getShopId());
        shopSessionInfo.setEmployeeId(shopEmployee.getEmployeeId());
        shopSessionInfo.setEmployeeNickname(shopEmployee.getNickname());
        UserSessionInfo userSessionInfo = new UserSessionInfo();
        userSessionInfo.setUserId(user.getUserId());
        userSessionInfo.setPic(user.getPic());
        userSessionInfo.setNickName(user.getNickName());
        PageParam<ImMsgBizUserHistory> pageParam = new PageParam<>();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageParam.setCurrent(messageInfo.getCurrent());
            pageParam.setSize(messageInfo.getSize());
        }
        Page<ImMsgBizUserHistory> history = this.page(pageParam, new LambdaQueryWrapper<ImMsgBizUserHistory>()
                .eq(ImMsgBizUserHistory::getSendType, SendType.SHOP).eq(ImMsgBizUserHistory::getBizId, shopUser.getShopId()).eq(ImMsgBizUserHistory::getUserId, user.getUserId()).orderByDesc(ImMsgBizUserHistory::getId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getRecords();
        List<MsgItem> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItem msgItem = this.getUserShopMsgItem(shopSessionInfo, userSessionInfo, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        Page<MsgItem> msgItemPage = new Page<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setRecords(msgItems);
        return msgItemPage;
    }

    @Override
    public Page<MsgItem> getPlatformUserHistory(YamiSysUser sysUser, MessageInfo messageInfo, User user) {
        SysSessionInfo sysSessionInfo = new SysSessionInfo();
        sysSessionInfo.setUserId(sysUser.getUserId());
        sysSessionInfo.setNickName(sysUser.getNickName());
        UserSessionInfo userSessionInfo = new UserSessionInfo();
        userSessionInfo.setUserId(user.getUserId());
        userSessionInfo.setPic(user.getPic());
        userSessionInfo.setNickName(user.getNickName());
        PageParam<ImMsgBizUserHistory> pageParam = new PageParam<>();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageParam.setCurrent(messageInfo.getCurrent());
            pageParam.setSize(messageInfo.getSize());
        }
        Page<ImMsgBizUserHistory> history = this.page(pageParam, new LambdaQueryWrapper<ImMsgBizUserHistory>()
                .eq(ImMsgBizUserHistory::getSendType, SendType.PLATFORM).eq(ImMsgBizUserHistory::getBizId, sysUser.getUserId()).eq(ImMsgBizUserHistory::getUserId, user.getUserId()).orderByDesc(ImMsgBizUserHistory::getId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getRecords();
        List<MsgItem> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItem msgItem = this.getUserPlatformMsgItem(sysSessionInfo, userSessionInfo, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        Page<MsgItem> msgItemPage = new Page<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setRecords(msgItems);
        return msgItemPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markUserPlatformRead(MessageInfo messageInfo, Long bizId, String userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getOne(new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getSendType, SendType.PLATFORM).eq(ImMsgBizUser::getBizId, bizId).eq(ImMsgBizUser::getUserId, userId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getTzImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.EMPLOYEE)) {
                    if (Objects.equals(imMsgBizUserHistory.getUserUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setUserUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatchById(imMsgBizUserHistories);
            Integer userUnreadNum = this.count(new LambdaQueryWrapper<ImMsgBizUserHistory>()
                    .eq(ImMsgBizUserHistory::getTzImMsgBizUserId, imMsgBizUser.getId())
                    .eq(ImMsgBizUserHistory::getUserUnread, MsgRead.UNREAD).eq(ImMsgBizUserHistory::getWhoSend, WhoSend.EMPLOYEE));
            imMsgBizUser.setUserUnreadNum(userUnreadNum);
            imMsgBizUserService.updateById(imMsgBizUser);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markUserShopRead(MessageInfo messageInfo, Long bizId, String userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getOne(new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getSendType, SendType.SHOP).eq(ImMsgBizUser::getBizId, bizId).eq(ImMsgBizUser::getUserId, userId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getTzImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.EMPLOYEE)) {
                    if (Objects.equals(imMsgBizUserHistory.getUserUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setUserUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatchById(imMsgBizUserHistories);
            Integer userUnreadNum = this.count(new LambdaQueryWrapper<ImMsgBizUserHistory>()
                    .eq(ImMsgBizUserHistory::getTzImMsgBizUserId, imMsgBizUser.getId())
                    .eq(ImMsgBizUserHistory::getUserUnread, MsgRead.UNREAD).eq(ImMsgBizUserHistory::getWhoSend, WhoSend.EMPLOYEE));
            imMsgBizUser.setUserUnreadNum(userUnreadNum);
            imMsgBizUserService.updateById(imMsgBizUser);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markShopUserRead(MessageInfo messageInfo, YamiShopUser shopUser, String userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getOne(new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getSendType, SendType.SHOP).eq(ImMsgBizUser::getBizId, shopUser.getShopId()).eq(ImMsgBizUser::getUserId, userId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getTzImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.USER)) {
                    if (Objects.equals(imMsgBizUserHistory.getEmployeeUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setEmployeeUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatchById(imMsgBizUserHistories);
            // 更新店铺未读条数
            Integer bizUnreadNum = this.count(new LambdaQueryWrapper<ImMsgBizUserHistory>()
                    .eq(ImMsgBizUserHistory::getTzImMsgBizUserId, imMsgBizUser.getId())
                    .eq(ImMsgBizUserHistory::getEmployeeUnread, MsgRead.UNREAD).eq(ImMsgBizUserHistory::getWhoSend, WhoSend.USER));
            imMsgBizUser.setBizUnreadNum(bizUnreadNum);
            imMsgBizUserService.updateById(imMsgBizUser);
            // 更新客服未读条数
            ImMsgBizEmployeeRecent imMsgBizEmployeeRecent = imMsgBizEmployeeRecentService.getOne(new LambdaQueryWrapper<ImMsgBizEmployeeRecent>()
                    .eq(ImMsgBizEmployeeRecent::getSendType, SendType.SHOP)
                    .eq(ImMsgBizEmployeeRecent::getBizId, shopUser.getShopId()).eq(ImMsgBizEmployeeRecent::getUserId, userId).eq(ImMsgBizEmployeeRecent::getEmployeeId, shopUser.getEmployeeId()));
            Integer employeeUnreadNum = this.count(new LambdaQueryWrapper<ImMsgBizUserHistory>()
                    .eq(ImMsgBizUserHistory::getTzImMsgBizUserId, imMsgBizUser.getId())
                    .eq(ImMsgBizUserHistory::getEmployeeId, shopUser.getEmployeeId()).eq(ImMsgBizUserHistory::getEmployeeUnread, MsgRead.UNREAD).eq(ImMsgBizUserHistory::getWhoSend, WhoSend.USER));
            imMsgBizEmployeeRecent.setEmployeeUnreadNum(employeeUnreadNum);
            imMsgBizEmployeeRecentService.updateById(imMsgBizEmployeeRecent);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markPlatformUserRead(MessageInfo messageInfo, YamiSysUser sysUser, String userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getOne(new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getSendType, SendType.PLATFORM).eq(ImMsgBizUser::getBizId, sysUser.getUserId()).eq(ImMsgBizUser::getUserId, userId));
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getTzImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.USER)) {
                    if (Objects.equals(imMsgBizUserHistory.getEmployeeUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setEmployeeUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatchById(imMsgBizUserHistories);
            Integer bizUnreadNum = this.count(new LambdaQueryWrapper<ImMsgBizUserHistory>()
                    .eq(ImMsgBizUserHistory::getTzImMsgBizUserId, imMsgBizUser.getId())
                    .eq(ImMsgBizUserHistory::getEmployeeUnread, MsgRead.UNREAD).eq(ImMsgBizUserHistory::getWhoSend, WhoSend.USER));
            imMsgBizUser.setBizUnreadNum(bizUnreadNum);
            imMsgBizUserService.updateById(imMsgBizUser);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveUserPlatformHistory(MessageInfo messageInfo, Long bizId, String userId) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, 0L, messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveUserShopHistory(MessageInfo messageInfo, Long bizId, String userId, Long employeeId) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, employeeId, messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveShopUserHistory(MessageInfo messageInfo, YamiShopUser shopUser) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.SHOP, shopUser.getShopId(), messageInfo.getToId(), shopUser.getEmployeeId(), messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory savePlatformUserHistory(MessageInfo messageInfo, YamiSysUser sysUser) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.PLATFORM, sysUser.getUserId(), messageInfo.getToId(), 0L, messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveUserPlatformOfflineReply(MessageInfo messageInfo, Long bizId, String userId) {
        // 存入用户留言
        this.saveHistory(messageInfo.getSendType(), bizId, userId, 0L, messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        // 没有在线客服，系统进行自动回复
        String content = "系统：当前没有在线客服，请留言。";
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, 0L, MsgType.TEXT, content, WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveUserShopOfflineReply(MessageInfo messageInfo, Long bizId, String userId) {
        // 存入用户留言
        ShopEmployee shopEmployee = shopEmployeeService.getOne(new LambdaQueryWrapper<ShopEmployee>().eq(ShopEmployee::getShopId, bizId).eq(ShopEmployee::getType, 0));
        this.saveHistory(messageInfo.getSendType(), bizId, userId, shopEmployee.getEmployeeId(), messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        // 没有在线客服，系统进行自动回复
        String content = "系统：当前没有在线客服，请留言。";
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, shopEmployee.getEmployeeId(), MsgType.TEXT, content, WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, ImMsgBizUserHistory> saveUserShopFirstReply(MessageInfo messageInfo, ShopSessionInfo shopSessionInfo, Long bizId, String userId) {
        Map<String, ImMsgBizUserHistory> map = new HashMap<>(16);
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, shopSessionInfo.getEmployeeId(), messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        map.put("user", imMsgBizUserHistory);
        // 写入一条系统消息（某某客服为你服务）
        String content = "系统：" + shopSessionInfo.getEmployeeNickname() + "客服为您服务";
        ImMsgBizUserHistory imMsgBizUserHistory2 = this.saveHistory(messageInfo.getSendType(), bizId, userId, shopSessionInfo.getEmployeeId(), MsgType.TEXT, content, WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory2);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory2);
        map.put("shop", imMsgBizUserHistory2);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveShopChangeEmployeeReply(YamiShopUser shopUser, ShopSessionInfo shopSessionInfo, UserSessionInfo userSessionInfo) {
        String content = "系统：转接成功：" + shopSessionInfo.getEmployeeNickname() + "客服为您服务";
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.SHOP, shopUser.getShopId(), userSessionInfo.getUserId(), shopSessionInfo.getEmployeeId(), MsgType.TEXT, content, WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

}
